package com.z0ltrix.CallLogr;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SettingsSQLLite {
	
	private static final String DATABASE_NAME = "CallLogr_DB";
	private static final String DATABASE_TABLE = "Settings";
	private static final int DATABASE_VERSION = 1;
	
	public static final String KEY_SETTING_NAME = "call_setting_name";
	public static final String KEY_SETTING_VALUE = "call_setting_value"; 
	public static final String TAG = "SettingsSQLLite";
	
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;
	private Context mContext;
	
	private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE 
									+ " ( " + KEY_SETTING_NAME + " TEXT, " 
									+ KEY_SETTING_VALUE + " TEXT);";
	
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
		
		DatabaseHelper(Context context){
			super(context, DATABASE_NAME, null, DATABASE_VERSION );
			
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			
			Log.i(TAG, "creating database: " + DATABASE_NAME);
			db.execSQL(DATABASE_CREATE);
			
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + "to " + newVersion + 
					". ALL OLD DATA WILL BE LOST.");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
			onCreate(db);
			
		}
		
	}
	
	public SettingsSQLLite(Context context){
		this.mContext = context;
	}
	
	public SettingsSQLLite open() throws SQLException{
		Log.i(TAG, "Opening database connection...");
		mDbHelper = new DatabaseHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		
		return this;
		
	}
	
	
	public void close(){
		mDbHelper.close();
	}
	
	public long createEntry(String setting, String value){
		
		Log.i(TAG, "Inserting a new setting...");
		ContentValues content = new ContentValues();
		content.put(KEY_SETTING_NAME, setting);
		content.put(KEY_SETTING_VALUE, value);
		
		return mDb.insert(DATABASE_NAME, null, content);
	}
	
	public Cursor fetchSettings(String setting_name) throws SQLException{
		
		Cursor cursor = mDb.query(true, DATABASE_TABLE, new String[]{KEY_SETTING_NAME, KEY_SETTING_VALUE },
								KEY_SETTING_VALUE + " = " + setting_name, 
								null, null, null, null, null);
		
		return cursor;
		
	}
	
	
	public boolean updateSettings(String setting_name, String setting_value){
		
		ContentValues content = new ContentValues();
		content.put(KEY_SETTING_VALUE, setting_value);
		
		return mDb.update(DATABASE_TABLE, content, KEY_SETTING_NAME + " = " + setting_name, null) > 0;
	}
	
	
	
	

}
